const req = require('request');
const mysql = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '123456',
    database : 'qrsoft_v1_tangshi'
});
connection.connect();
var wxAddApi = 'https://api.weixin.qq.com/tcb/databaseadd?';
const accessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxac7b5cecf3de8928&secret=f90e3d5fdb8c3a9ab18bde522cf1c44e';

getAccessToken();

function getAccessToken(){
    req.get({
      url : accessTokenUrl,
      encoding : 'utf-8'
    }, (err, res, body)=>{
      if(!err && res.statusCode == 200){
          var obj = JSON.parse(body);
          var access_token = obj['access_token'];
          wxAddApi+=("access_token="+access_token);
          getArticle();
      }
    })
}

// getArticle();
function getArticle(){
    var sql = "SELECT qa.id,qa.title,qa.content,qam.tags,qam.author,qam.dynasty "+
    "FROM qr_article qa JOIN qr_article_model_6 qam ON qa.id =qam.article_id "+
    "WHERE qa.model_type = 6;"; 
    connection.query(sql,function (err, result) {
        if(err){
          console.log('[SELECT ERROR] - ',err.message);
          return;
        } 
        var item = result[0];
        insertwxdb(item.id,item.content,item.author,item.title,item.tags);
    });
}

function insertwxdb(uid,content,author,title,tags){
    var obj ={
        "env":"zhangchun-stjwb",
        "query": "db.collection(\"smallTechnology_posts\").add({data: [{_id:\""+uid+"\",content:\""+encodeURIComponent(content)+"\",author:\""+author+"\",defaultImageUrl:\"\",title:\""+title+"\",isShow:1,contentType:\"html\",createTime:\"2020/3/28\",totalVisits:0,totalZans:0,sourceFrom:\"\",digest:\"\",timestamp:\""+1585372387889+"\",label:\""+tags+"\",classify:\"6\"}]})"
    };
    console.log(obj);
    req({
        url: wxAddApi,
        method: "POST",
        json: true,
        headers: {
        "content-type": "application/json",
        },
        body: obj
        }, function(error, response, body) { 
            console.log(error);
            console.log(body);
        });
}

